package com.nettylern.netty.msgpack编解码;

import com.nettylern.netty.pojo.UserInfo;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author liliang
 * @date 2019/12/5.
 */
public class EchoClientHandler extends ChannelInboundHandlerAdapter {

    private final int num;

    EchoClientHandler(int num) {
        this.num = num;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        UserInfo[] userInfos = initUserInfo();
        for (UserInfo userInfo : userInfos) {
            ctx.write(userInfo);
        }
        ctx.flush();
    }

    private UserInfo[] initUserInfo() {
        UserInfo[] userInfoArray = new UserInfo[num];
        UserInfo userInfo;
        for (int i = 0; i < num; i++) {
            userInfo = new UserInfo();
            userInfo.setAge(i);
            userInfo.setName("王大锤------>" + i);
            userInfoArray[i] = userInfo;
        }
        return userInfoArray;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Client receive the msgpack message :" + msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
